package com.sofwin.controller;

import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.Log;
import com.sofwin.base.ResponseEntity;
import com.sofwin.pojo.SysMenu;
import com.sofwin.pojo.SysRole;
import com.sofwin.service.MenuService;
import com.sofwin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @packageName: com.sofwin.controller
 * @author: andyliu
 * @date: 2022/8/12 9:24
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleServce;
    @Autowired
    private MenuService menuService;
    @GetMapping("/toList")
    public String toList(){
        return "role/list";
    }
    @GetMapping("/toEdit")
    public String toEdit(Integer id, Model model){
        if(id!=null){
            model.addAttribute("role",roleServce.queryById(id));
            model.addAttribute("id",id);
        }
        return "role/edit";
    }
    @GetMapping()
    @ResponseBody
    @Log(module = "角色查询",operatorType = 1)
    public ResponseEntity data(SysRole role,
                               @RequestParam(name = "pageNumber",required = true,defaultValue = "1") Integer pageNumber,
                               @RequestParam(name = "pageSize",required = true,defaultValue = Constants.PAGE_SIZE) Integer pageSize){
        PageInfo<SysRole> page = roleServce.queryByPage(role, pageNumber, pageSize);
        return ResponseEntity.success(page);
    }

    @GetMapping("/menus")
    @ResponseBody
    public ResponseEntity menus(SysMenu menu,Integer roleId){
        if(roleId==null) {
            // 如果是新增  checked = false
            List<SysMenu> menus = menuService.queryMenus(menu);
            return ResponseEntity.success(menus);
        }
        List<SysMenu> menus = menuService.queryMenusByRoleId(roleId);
        // 如果是编辑  有的true | false
        return ResponseEntity.success(menus);
    }
    @PostMapping("/save")
    @ResponseBody
    public ResponseEntity save(SysRole role,Integer[] menuIds){
        boolean status = roleServce.saveRole(role,menuIds);
        if(status){
            return ResponseEntity.success();
        }
        return ResponseEntity.error();
    }
}
